define(function (require) {

    require('../../../c/base/index');

    require('../../../c/nav/index');

    var adv = {
        data: {},
        init: function () {
            //初始化菜单选中效果
            $(".fa-circle-o").each(function () {
                if ($(this).parents("a").text() == "pos广告管理") {
                    $(this).parents("a").parents("li").addClass("active");
                }
            });
            this.initTable();
            this.initValidator();
            this.bindEvent();
            this.initUpload();
        },
        /**
         * 执行查询操作.
         */
        doSearch: function () {
            $('#table').DataTable().ajax.reload();
        },
        /**
         * 初始化列表
         */
        initTable: function () {
            var self = this;
            $("#table").dataTable({
                "oLanguage": CRM.pageConfig,
                "sScrollX": "100%",   //表格的宽度
                "sScrollXInner": "100%",   //表格的内容宽度
                "bScrollCollapse": true,  //当显示的数据不足以支撑表格的默认的高度时，依然显示纵向的滚动条。(默认是false)
                "bPaginate": true,  //是否显示分页
                "bLengthChange": false,  //每页显示的记录数
                "bFilter": false, //搜索栏
                "bSort": false, //是否支持排序功能
                "bInfo": false, //显示表格信息
                "bAutoWidth": false,  //自适应宽度
                "bServerSide": true,//开启服务端处理
                "sAjaxSource": CRM.getOuterUrl('/poscrm/api/ads/queryAdsImages'),
                "fnInitComplete": function () {
                    this.fnAdjustColumnSizing(true);
                },
                "fnServerData": function (sSource, aoData, fnCallback) {
                    var _data = {};
                    $($("#J_Search").serializeArray()).each(function () {
                        _data[this.name] = this.value;
                    });
                    _data.pageNo = aoData[3].value / aoData[4].value + 1;
                    _data.pageSize = aoData[4].value;
                    if (_data.typeList == 1) {
                        _data.typeList = [1]
                    } else {
                        _data.typeList = [2, 3]
                    }

                    var dataString = JSON.stringify(_data);
                    CRM.request({
                        "type": 'POST',
                        "url": sSource,
                        "dataType": "json",
                        contentType: "application/json",
                        xhrFields: {
                            withCredentials: true
                        },
                        "data": dataString,
                        contentType: "application/json",
                        "success": function (req) {
                            if (req.status) {
                                var resultData = CRM.getDataTabelDtaObject();
                                if (req.entry) {
                                    resultData.iTotalDisplayRecords = 999999;
                                    resultData.iTotalRecords = 999999;
                                    $.each(req.entry, function (key, entry) {
                                        resultData.aaData.push(entry)
                                        self.data[entry.id] = entry;
                                    });
                                } else {
                                    CRM.showDialog(req.message);
                                }
                                fnCallback(resultData);
                            } else {
                                CRM.showDialog(req.message);
                            }
                        }
                    });
                },
                //"aaSorting": [[1, "asc"]],  //给列表排序 ，第一个参数表示数组 (由0开始)。1 表示Browser列。第二个参数为 desc或是asc
                "aoColumns": [

                    {
                        "sTitle": "广告类型",
                        "mDataProp": "type",
                        "mRender": function (data, type, row) {
                            var html = '未知类型';
                            if (data == 1) {
                                html = '小图片';
                            } else if (data == 2) {
                                html = '大图片';
                            } else if (data == 3) {
                                html = "视频";
                            }
                            return html;
                        }
                    },
                    {
                        "sTitle": "图片",
                        "mDataProp": "type",
                        "mRender": function (data, type, row) {
                            var html = "";
                            if (data == 1) {
                                html = '<img src="' + row.url + '" alt="" width="100" height="210"/>';
                            } else if (data == 2) {
                                html = '<img src="' + row.url + '" alt="" width="200" height="150"/>';
                            } else if (data == 3) {
                                html = '<video src="' + row.url + '" alt="" width="200" height="150" controls="controls"/>';
                            }
                            return html;
                        }
                    },
                    {
                        "sTitle": "操作",
                        "bSortable": true,
                        "mDataProp": "id",
                        "mRender": function (data, type, row) {
                            var html = '<button type="button" class="btn btn-danger" onclick="javascript:deleteAdv(\'' + data + '\')">删 除</button>';
                            return html;
                        }
                    }

                ], //列设置，表有几列，数组就有几项
                "bStateSave": true, //保存状态到cookie *************** 很重要 ， 当搜索的时候页面一刷新会导致搜索的消失。使用这个属性就可避免了
                "sPaginationType": "simple" //分页，一共两种样式，full_numbers和two_button(默认)

            });
        },
        /**
         * 表单验证初始化
         */
        initValidator: function () {
            $('#modify_form').bootstrapValidator({
                message: '输入错误',
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    version: {
                        validators: {
                            message: '版本号错误',
                            callback: {
                                message: '版本号格式错误',
                                callback: function (value, validator) {
                                    var reg = /^[0-9]{1,2}.[0-9]{1,2}.[0-9]{1,2}$/;
                                    if (reg.test(value)) {
                                        return true;
                                    } else {
                                        return false;
                                    }
                                }
                            }
                        }
                    }
                }
            });
        },
        bindEvent: function () {
            var self = this;
            $("#search_btn").on('click', function () {
                self.doSearch();
            });
            $("#save").on('click', function () {
                self.save();
            });
            $("#add_btn").on('click', function () {
                self.openModify();
            });
            $("#type").on('change', function () {
                self.changeType();
            });
        },
        /**
         * 改变图片类型
         */
        changeType: function () {
            $("#url_img_small").hide();
            $("#url_img_big").hide();
            $("#url_video").hide();
            if ($("#type").val() == 1) {
                $("#url_img_small").show();
            } else if ($("#type").val() == 2) {
                $("#url_img_big").show();
            } else if ($("#type").val() == 3) {
                $("#url_video").show();
            }
        },
        /**
         * 打开编辑框
         * @param id
         */
        openModify: function () {
            var self = this;
            $('#modify_dialog').modal('show');
            $("#url_img_small").attr("src", "");
            $("#url_img_big").attr("src", "");
            $("#url_video").attr("src", "");
            $('#modify_dialog').on('shown.bs.modal', function (e) {
                CRM.clearForm("modify_form");
                $("#type").val(1);
                $("#url_img_small").show();
                $("#url_img_big").hide();
                $("#url_video").hide();
                $("#modify_form").data('bootstrapValidator').resetForm();
            });
        },
        /**
         * 保存操作
         */
        save: function () {
            var self = this;
            $("#modify_form").data('bootstrapValidator').resetForm();
            $("#modify_form").data('bootstrapValidator').validate();
            if ($("#modify_form").data('bootstrapValidator').isValid()) {
                var _url = CRM.getOuterUrl("/poscrm/api/ads/insertAdsImage");
                var dataString, _data = {};
                $($("#modify_form").serializeArray()).each(function () {
                    _data[this.name] = this.value;
                });
                if ($("#type").val() == 1) {
                    _data.url = $("#url_img_small").attr("src");
                } else if ($("#type").val() == 2) {
                    _data.url = $("#url_img_big").attr("src");
                } else if ($("#type").val() == 3) {
                    _data.url = $("#url_video").attr("src");
                }
                if (!_data.url) {
                    CRM.showDialog("请上传广告文件！");
                    return;
                }
                dataString = JSON.stringify(_data);
                CRM.request({
                    "type": 'POST',
                    "url": _url,
                    "dataType": "json",
                    contentType: "application/json",
                    "data": dataString,
                    "success": function (req) {
                        if (req.status) {
                            $('#modify_dialog').modal('hide');
                            CRM.showDialog("保存成功！");
                            self.doSearch();
                        } else {
                            CRM.showDialog(req.message);
                        }
                    }
                });
            }
        },
        /**
         * 删除
         * @param id
         */
        deleteAdv: function (id) {
            var _url = CRM.getOuterUrl("/poscrm/api/ads/deleteAdsImage");
            if (!confirm('确认删除？')) {
                return;
            }
            dataString = JSON.stringify({
                id: id
            });
            CRM.request({
                "type": 'POST',
                "url": _url,
                "dataType": "json",
                contentType: "application/json",
                "data": dataString,
                "success": function (req) {
                    if (req.status) {
                        $('#modify_dialog').modal('hide');
                        CRM.showDialog("删除成功！");
                        self.doSearch();
                    } else {
                        CRM.showDialog(req.message);
                    }
                }
            });
        },
        /**
         * 文件上传组件初始化
         */
        initUpload: function () {
            var self = this;
            $("#url").fileupload({
                url: CRM.getOuterUrl('/itemcenter/upload/server'), //文件上传地址，当然也可以直接写在input的data-url属性内
                //formData:{param1:"p1",param2:"p2"},//如果需要额外添加参数可以在这里添加
                done: function (e, req) {
                    //done方法就是上传完毕的回调函数，其他回调函数可以自行查看api
                    //注意result要和jquery的ajax的data参数区分，这个对象包含了整个请求信息
                    //返回的数据在result.result中，假设我们服务器返回了一个json对象
                    CRM.unLoadMask();
                    if (req.result.status) {
                        if (req.result.entry) {
                            if ($("#type").val() == 1) {
                                $("#url_img_small").attr("src", self.getUrlImg() + req.result.entry);
                            } else if ($("#type").val() == 2) {
                                $("#url_img_big").attr("src", self.getUrlImg() + req.result.entry);
                            } else if ($("#type").val() == 3) {
                                $("#url_video").attr("src", self.getUrlImg() + req.result.entry);
                                document.getElementById("url_video").play();
                            }
                        }
                    } else {
                        CRM.showDialog(req.result.message)
                    }

                }
            }).bind('fileuploadstart', function (e) {
                CRM.loadMask($("#modify_dialog"));
            });
        },
        /**
         * 删除对应的图片
         */
        deleteImg: function () {
            if ($("#type").val() == 1) {
                $("#url_img_small").attr("src", "");
            } else if ($("#type").val() == 2) {
                $("#url_img_big").attr("src", "");
            } else if ($("#type").val() == 3) {
                $("#url_video").attr("src", "");
            }
        },
        getUrlImg: function () {
            // 日常环境
            if (!!~location.host.indexOf('daily.')) {
                //return 'http://imgdaily.52shangou.com/img/';
                return 'http://imgsize.52shangou.com/img/'
            }
            // 线上环境 & 灰度环境
            else {
                return 'http://imgsize.52shangou.com/img/'
            }
        }

    };

    window.doSearch = $.proxy(adv.doSearch, adv);
    window.deleteAdv = $.proxy(adv.deleteAdv, adv);
    window.deleteImg = $.proxy(adv.deleteImg, adv);
    adv.init();
});